package com.bill99.http.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.*;
import org.apache.log4j.Logger;
import org.springframework.util.CollectionUtils;

import com.bill99.util.PageData;

import java.io.IOException;
import java.util.Map;

/**
 * 同程API公有类
 * 
 * @author HarryWang
 * 
 */
public class HttpURLUtils {
	/** 日志 */
	public static final Logger logger = Logger.getLogger(HttpURLUtils.class);
	
	/**
	 * 以post方式发送Josn
	 * 
	 * @param url
	 *            同程的API接口的url
	 * @param json
	 *            json参数数据
	 * @return 返回接口的返回值
	 * @throws HttpException
	 * @throws IOException
	 */
	public static String postJson(String url, String json, String accessId,
			String md5, String requestContent, Map<String, String> parameterMap, PageData pd)
			throws HttpException, IOException {
		String strResponse = null;
		PostMethod hm = new PostMethod(url);
//		hm.addRequestHeader("X-ACCESS-ID", accessId);// 在请求头里添加自定义头
//		hm.addRequestHeader("X-FINGERPRINT", md5);// md5的值作为X-FINGERPRINT
		hm.setRequestHeader("Content-type", "application/json;charset=UTF-8");
		hm.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
		if (!CollectionUtils.isEmpty(parameterMap)) {
			for (Map.Entry<String, String> entry : parameterMap.entrySet()) {
				hm.addParameter(entry.getKey(), entry.getValue());
			}
		}
		if (StringUtils.isNotEmpty(requestContent)) {
			hm.addParameter("RequestContent", requestContent);
		}

		HttpClient httpClient = new HttpClient();

		// 代理
//		if("true".equalsIgnoreCase(pd.getPdKey("switch"))){
//		    if(pd.containsKey("host") && pd.containsKey("port")){
//		        httpClient.getHostConfiguration().setProxy(pd.getPdKey("host"), Integer.valueOf(pd.getPdKey("port")));
//		        httpClient.getParams().setAuthenticationPreemptive(true);
//		    }
//		}

		HttpConnectionManagerParams managerParams = httpClient
				.getHttpConnectionManager().getParams();
		// 设置连接超时时间(单位毫秒)
		managerParams.setConnectionTimeout(Integer.valueOf(StringUtils.isBlank(pd.getPdKey("connect"))?"7000":pd.getPdKey("connect")));
		// 设置读数据超时时间(单位毫秒)
		managerParams.setSoTimeout(Integer.valueOf(StringUtils.isBlank(pd.getPdKey("response"))?"15000":pd.getPdKey("response")));

		if (logger.isInfoEnabled()) {
			logger.info("post json  :  --->" + json + "<----");
		}
		if (StringUtils.isNotEmpty(json)) {
			RequestEntity requestEntity = new StringRequestEntity(json,
					"text/xml", "UTF-8");
			hm.setRequestEntity(requestEntity);
		}
		
		int statusCode = httpClient.executeMethod(hm);
		if (logger.isInfoEnabled()) {
			logger.info("statusCode  :  --->" + statusCode + "<----");
		}
		if (statusCode != HttpStatus.SC_OK) {
			// 释放连接
			hm.releaseConnection();
			throw new IllegalStateException("Method failed: "
					+ hm.getStatusLine());
		} else {
			strResponse = hm.getResponseBodyAsString();
		}

		// 释放连接
		hm.releaseConnection();
		return strResponse;
	}

	/**
	 * 以post方式发送Josn
	 * 
	 * @param url
	 *            同程的API接口的url
	 * @param json
	 *            json参数数据
	 * @return 返回接口的返回值
	 * @throws HttpException
	 * @throws IOException
	 */
	public static String postJson(String url, String json) throws HttpException,
			IOException {
		String strResponse =null;
		PostMethod hm = new PostMethod(url);
		HttpClient httpClient = new HttpClient();
		HttpConnectionManagerParams managerParams = httpClient
				.getHttpConnectionManager().getParams();
		// 设置连接超时时间(单位毫秒)
		managerParams.setConnectionTimeout(30000);
		// 设置读数据超时时间(单位毫秒)
		managerParams.setSoTimeout(120000);
		if (logger.isInfoEnabled()) {
			logger.info("post json  :  --->" + json + "<----");
		}
		if (StringUtils.isNotEmpty(json)) {
			RequestEntity requestEntity = new StringRequestEntity(json,
					"text/xml", "UTF-8");
			hm.setRequestEntity(requestEntity);
			int statusCode = httpClient.executeMethod(hm);
			if (logger.isInfoEnabled()) {
				logger.info("statusCode  :  --->" + statusCode + "<----");
			}
			if (statusCode != HttpStatus.SC_OK) {
				// 释放连接
				hm.releaseConnection();
				throw new IllegalStateException("Method failed: "
						+ hm.getStatusLine());
			}else{
				strResponse=hm.getResponseBodyAsString();
			}
		}
		// 释放连接
		hm.releaseConnection();
		return strResponse;
	}
}
